﻿/******************************************************
* author :  cwj
* email  :  chenwenji_360@live.com 
* history:  created by cwj 2015/7/16 16:14:17 
* clrversion :4.0.30319.18444
******************************************************/

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Machine.DataAccess.Common.ORM
{
    class DynamicAssignment
    {
        private static Lazy<DynamicAssignment> _instance = new Lazy<DynamicAssignment>(() =>
        {
            return new DynamicAssignment();
        }, true);
        public static DynamicAssignment Instance { get { return _instance.Value; } }
        private DynamicAssignment() { }
        private ConcurrentDictionary<Type, PropertyInvokerDic> cache = new ConcurrentDictionary<Type, PropertyInvokerDic>();
        public PropertyInvokerDic GetDictionary(Type type)
        {
            if (type.Name.StartsWith("<>")) throw new NotSupportedException("不支持匿名类的数据赋值");
            if (!this.cache.ContainsKey(type))
            {
                var properties = type.GetProperties();
                var invokers = new PropertyInvokerDic(type);
                foreach (var property in properties)
                {
                    invokers.Add(property);
                }
                var fields = type.GetFields();
                foreach (var item in fields)
                {
                    invokers.Add(item);
                }
                cache.AddOrUpdate(type, invokers, (utype, uinvokes) => { return uinvokes; });
            }
            return cache[type];
        }

        public IPropertyInvoker GetInvoker(Type type, string name)
        {
            var temp = this.GetDictionary(type);
            return temp != null && temp.ContainsKey(name) ? temp[name] : null;
        }
        public IPropertyInvoker GetInvoker<TType>(string name)
        {
            var type = typeof(TType);
            return this.GetInvoker(type, name);
        }
    }
}
